package com.net.xpay.admin.secutiry;

import com.google.common.collect.Lists;
import com.net.xpay.core.constant.AdminWebConstant;
import com.net.xpay.core.helper.DomainHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
  on 07/02/2018.
 */
@Component
public class SuccessLogoutHandler implements LogoutSuccessHandler {
    @Autowired
    private DomainHelper domainHelper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        removeCookie(request, response, Lists.newArrayList(AdminWebConstant.REMEMBER_ME_COOKIE_NAME));

        String tpl = request.getParameter("tpl");

        redirectResponse(response, tpl);
    }

    private void removeCookie(HttpServletRequest request, HttpServletResponse response, List<String> cookiesToClear) {
        String cookieDomain = domainHelper.getCookieDomain(request);

        for (String cookieName : cookiesToClear) {
            Cookie cookie = new Cookie(cookieName, null);
            String cookiePath = request.getContextPath() + "/";
            cookie.setPath(cookiePath);
            cookie.setMaxAge(0);
            cookie.setDomain(cookieDomain);
            response.addCookie(cookie);
        }
    }

    private void redirectResponse(HttpServletResponse response, String destination) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", destination);
    }
}
